package com.example.administrator.musicplayer;

import android.Manifest;
import android.app.Activity;
import android.app.LauncherActivity;
import android.content.pm.PackageManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.Manifest;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import com.example.administrator.musicplayer.bean.*;


public class MusicActivity extends Activity {

//    MP3File
    MediaPlayer mp=new MediaPlayer();
    private SeekBar seekBar;
    String song_path;
    int before_pos ;
    private int currentposition;
    private Timer timer;
    private TimerTask timerTask;
    private boolean isChanging = false;
    private boolean ifplay = false;
    private boolean iffirst = false;
    private View currentView;
    private ArrayList<String> list;
    private MusicAdapter adapter;
//    private MusicAdapter adapter;

    ListView li;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_music);
        if (ActivityCompat.checkSelfPermission( MusicActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(MusicActivity.this,
                    new String[] {
                    Manifest.permission.READ_EXTERNAL_STORAGE
                    }, 123);


            return;
        }
        if (ActivityCompat.checkSelfPermission( MusicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(MusicActivity.this,
                    new String[] {
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 123);


            return;
        }

        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder()
                    ;
            StrictMode.setVmPolicy(builder.build());
        }


        list = new ArrayList<String>(); //音乐列表
        ArrayList<com.example.administrator.musicplayer.bean.Music> list_name = new ArrayList<>();
        File sdpath= Environment.getExternalStorageDirectory(); //获得手机SD卡路径
        File path=new File(sdpath+"//Music//"); //获得SD卡的music文件夹
//返回以.mp3结尾的文件 (自定义文件过滤)
        File[ ] songFiles = path.listFiles( new MyFilter(".mp3") );

        for (File file :songFiles){
            String str = file.getAbsolutePath();


            try{

                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(str);
                String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
//                MediaPlayer mt = new MediaPlayer();
//                mt.setDataSource(str);
//                mt.prepare();
                String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
                String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
                int during_time = Integer.parseInt(duration);
                int minute = during_time/60000;
                int second = during_time/1000%60;
                String time =minute+":"+second;
                com.example.administrator.musicplayer.bean.Music music = new com.example.administrator.musicplayer.bean.Music(title,time,artist);
                list_name.add(music);
            }catch (Exception er)
            {
                Log.v("errot", er.toString());
            }

            list.add( file.getAbsolutePath() ); //获取文件的绝对路径
        }
//        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(MusicActivity.this,R.layout.music_item,list);
        adapter = new MusicAdapter(MusicActivity.this,R.layout.music_item,list_name);
        li=(ListView)findViewById(R.id.listView);
        li.setAdapter(adapter);
        li.setChoiceMode(ListView.CHOICE_MODE_SINGLE); //单选

        seekBar = (SeekBar)findViewById(R.id.sb);
        seekBar.setOnSeekBarChangeListener(new Myseekbar());
        li.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ImageView omv = view.findViewById(R.id.btn_img);
                if(currentView!=null)
                {

                    ImageView temp = currentView.findViewById(R.id.btn_img);
                    temp.setImageDrawable(getResources().getDrawable(R.drawable.menu));
                }


                omv.setImageDrawable(getResources().getDrawable(R.drawable.music));
                currentView = view;
                currentposition = position;
                song_path=list.get(currentposition);

                try{
                    if(mp.isPlaying())
                    {
                        mp.stop();
                    }
                    mp.reset(); //重置
                    mp.setDataSource(song_path);
                    mp.prepare(); //准备
                    mp.start();  //播放
                    seekBar.setMax(mp.getDuration());
                    timer = new Timer();
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if(isChanging) {
                                return;
                            }
                            seekBar.setProgress(mp.getCurrentPosition());
                        }
                    };
                    timer.schedule(timerTask,0,10);





                }catch (Exception e){

                }
            }
        });

        final ImageButton btnpause=(ImageButton)findViewById(R.id.ibtn1);
        btnpause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( song_path.isEmpty() )
                    Toast.makeText(getApplicationContext(), "先选收歌曲先听听,"+before_pos,
                            Toast.LENGTH_SHORT).show();
                if( mp.isPlaying() ){
                    mp.pause(); //暂停
                    Toast.makeText(getApplicationContext(), "暂停了哦",
                            Toast.LENGTH_SHORT).show();
                    btnpause.setImageResource(R.drawable.stop);
                }else if( !song_path.isEmpty() ){
                    mp.start(); //继续播放
                    btnpause.setImageResource(R.drawable.play);
//                    seekBar.setMax(mp.getDuration());
//                    timer = new Timer();
//                    timerTask = new TimerTask() {
//                        @Override
//                        public void run() {
//                            if(isChanging) {
//                                return;
//                            }
//                            seekBar.setProgress(mp.getCurrentPosition());
//                        }
//                    };
//                    timer.schedule(timerTask,0,10);



                }
            }
        });
        ImageButton btn_b = (ImageButton)findViewById(R.id.btn_b);
        ImageButton btn_n = (ImageButton)findViewById(R.id.btn_n);
        btn_n.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int visiblePosition = li.getFirstVisiblePosition();
                        View temp2 = li.getChildAt(currentposition);
                        ImageView temp_i = temp2.findViewById(R.id.btn_img);
                        temp_i.setImageDrawable(getResources().getDrawable(R.drawable.menu));
                        if(currentposition==li.getCount()-1)
                        {
                            currentposition = -1;
                        }
                        currentposition++;
                        String url  = list.get(currentposition);
//                        li.setItemChecked(currentposition,true);
//                        View view = (View)li.getItemAtPosition(currentposition);
                        View temp = li.getChildAt(currentposition);
                        currentView = temp;
                        ImageView temp2_i = temp.findViewById(R.id.btn_img);
                        temp2_i.setImageDrawable(getResources().getDrawable(R.drawable.music));

                        Toast.makeText(getApplicationContext(),"666666"+url,Toast.LENGTH_SHORT).show();
                        try{
                            mp.reset();
                            mp.setDataSource(url);
                            mp.prepare();
                            mp.start();
                        }catch (Exception e)
                        {
                            Log.v("log",e.toString());
                        }


                    }
                }
        );
        btn_b.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        int visiblePosition = li.getFirstVisiblePosition();
                        View temp2 = li.getChildAt(currentposition);
                        ImageView temp_i = temp2.findViewById(R.id.btn_img);
                        temp_i.setImageDrawable(getResources().getDrawable(R.drawable.menu));
                        if(currentposition==0)
                        {
                            currentposition = li.getCount();
                        }

                        String url  = list.get(--currentposition);
                        Toast.makeText(getApplicationContext(),"666666"+url,Toast.LENGTH_SHORT).show();
//                        li.setItemChecked(currentposition,true);
//                        visiblePosition = li.getFirstVisiblePosition();
                        View temp = li.getChildAt(currentposition);
                        currentView = temp;
                        ImageView temp2_i = temp.findViewById(R.id.btn_img);
                        temp2_i.setImageDrawable(getResources().getDrawable(R.drawable.music));
                        try{
                            mp.reset();
                            mp.setDataSource(url);
                            mp.prepare();
                            mp.start();
                            btnpause.setImageResource(R.drawable.play);
                        }catch (Exception e)
                        {
                            Log.v("log",e.toString());
                        }


                    }
                }
        );

    }
    class Myseekbar implements SeekBar.OnSeekBarChangeListener{
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
            isChanging=true;
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            mp.seekTo(seekBar.getProgress());
            isChanging=false;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mp!=null){
            timerTask.cancel();
            mp.stop();
            mp.release();

        }
        Toast.makeText(getApplicationContext(), "退出啦", Toast.LENGTH_SHORT).show();
    }

    public View getViewByPosition(int pos, ListView listView) {
        final int firstListItemPosition = listView.getFirstVisiblePosition();
        final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition ) {
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }
}
